/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: libevent_lib.c
 * Create Date: 2011-09-22 09:29:21
 *
 */

#include "action_lib.h"
#include "mem_lib.h"
#include "log_lib.h"
#include "conf_lib.h"

int last_thread = -1;

void on_accept(int fd, short ev, void *arg){
	int client_fd, tid, thread_num, err_len;
    char *err, *err_log;
	struct sockaddr_in client_addr;
	CQ_ITEM *item;
	LIBEVENT_THREAD *thread;
	socklen_t client_len;

    client_len = sizeof(client_addr);
	/* Accept the new connection. */
	client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
	if (client_fd == -1) {
        err = strerror(errno);
        err_len = strlen(err);
        err_log = calloc(1, err_len+100);
        sprintf(err_log, "accept-- %s", err);
		d_log(err_log);
        free(err_log);
		return;
	}
    
	item = cqi_new();

	thread_num = atoi(conf_get("thread_num"));
    tid = (last_thread + 1) % thread_num;
	thread = threads + tid;
    last_thread = tid;

    item->sfd = client_fd;

    cq_push(thread->new_conn_queue, item);

    if (write(thread->notify_write_fd, "", 1) != 1) {
        d_log("Writing to thread notify pipe");
    }
}

void conn_new(int sfd, struct event_base *base){
	/*conns = (conn *)calloc(1, sizeof(conn));*/
	conns = (conn *)SQLCalloc(1, sizeof(conn));
	conns->sfd = sfd;

	event_set(&conns->event, sfd, EV_READ|EV_PERSIST, on_accept, (void *)conns);
	event_base_set(base, &conns->event);
	event_add(&conns->event, 0);

}
/* vim: set ts=4 sw=4: */

